package com.business;

import java.io.FileWriter;
//import java.net.URLDecoder;
import java.util.ArrayList;

import org.apache.log4j.Logger;
//import com.util.CurrentUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 
 * @author bob yang
 * @date 2018年3月28日 
 * @TODO 将信息写入xml进行保存
 */
public class WriteInfoToXML
{
	private String fileName = "TJYZinfo";
	
	private static Logger logger = Logger.getLogger(WriteInfoToXML.class);

	public void writeInfoFirst(String projectPath,ArrayList<InfoBean> infoList) throws Exception
	{
		try
		{
			Document document = DocumentHelper.createDocument();
			Element xmlList = DocumentHelper.createElement("infoList");
			document.setRootElement(xmlList);
			for(int i=0;i<=infoList.size()-1;i++)
			{
				Element detail = xmlList.addElement("detail");
				//time 用于统计爬取信息总条数
				Integer time = i+1;
				detail.addAttribute("time", time.toString());
				detail.addAttribute("date", infoList.get(i).getDate());
				detail.addAttribute("href", infoList.get(i).getHref());
				detail.setText(infoList.get(i).getInfo());
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter xmlWriter = new XMLWriter(new FileWriter(projectPath + fileName + ".xml"), format);
			xmlWriter.write(document);
			xmlWriter.close();
		}
		catch (Exception e)
		{
			logger.error("WriteInfoToXML.java"+"-------->"+e.toString());
			throw new RuntimeException("写入Xml文件时出现异常");
		}

	}

//	public static void main(String[] args)
//	{
//		/*main方法用于调试*/
//		WriteInfoToXML wx = new WriteInfoToXML();
//		try
//		{
//			ArrayList<InfoBean> infoList = InfoCrawler.getInfo();
//			String projectPath = CurrentUtil.getProjectPath(WriteInfoToXML.class.getResource("../../").getPath().toString());
//			try 
//			{
//			  projectPath = URLDecoder.decode(projectPath, "utf-8");
//			} catch (Exception e) 
//			{
//			    e.printStackTrace();
//			}
//			wx.writeInfoFirst(projectPath, infoList);
//		}
//		catch (Exception e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

}
